<template>
  <div class="page-auth-content">
    <form class="page-conent"  @keypress.enter="submit" onsubmit="return false">
      <h3>{{by == type_enum.email ? '乐马号/邮箱登录' : ( by == type_enum.phone ? '手机号码登录' : 'Potato登录')}}</h3>
      <!-- phone -->
      <div v-if='by == type_enum.phone'>
        <div class="form-item fx fx-vc">
          <div class="fx form-label fx-vc fx-between" @click="changeAreaCode">
             <span>+{{form[type_enum.phone].area_code}}</span>
             <i class="arrow"></i>
          </div>
          <Input type="tel" class="flex" v-model="form[type_enum.phone].value" placeholder="请输入手机号码"/>
        </div>
        <div class="form-item fx fx-vc" v-if="!isByVer">
          <span class="form-label">登录密码</span>
          <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="form[type_enum.phone].password" />
        </div>
        <div class="form-item fx fx-vc" v-else>
          <span class="form-label">验证码</span>
          <Input type="tel" class="flex" v-model="form[type_enum.phone].ver_code" placeholder="请输入验证码"/>
          <a @click="getVerCode($event)" class="ver-code" :disabled='!form[type_enum.phone].value'>{{ver_time_text}}</a>
        </div>
      </div>
      <!-- potato -->
      <div v-else-if='by == type_enum.potato'>
        <div class="form-item fx fx-vc">
          <div class="fx form-label fx-vc fx-between" @click="changeAreaCode">
             <span>+{{form[type_enum.potato].area_code}}</span>
             <i class="arrow"></i>
          </div>
          <Input type="tel" class="flex" v-model="form[type_enum.potato].value" placeholder="请输入Potato"/>
        </div>
        <div class="form-item fx fx-vc" v-if="!isByVer">
          <span class="form-label">登录密码</span>
          <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="form[type_enum.potato].password" />
        </div>
        <div class="form-item fx fx-vc" v-else>
          <span class="form-label">验证码</span>
          <Input type="tel" class="flex" v-model="form[type_enum.potato].ver_code" placeholder="请输入验证码"/>
          <a @click="getVerCode($event)" class="ver-code" :disabled='!form[type_enum.potato].value'>{{ver_time_text}}</a>
        </div>
      </div>
      <!-- email -->
      <div v-else>
        <div class="form-item fx fx-vc">
          <span class="form-label">乐马号/邮箱</span>
          <Input type="email" class="flex"  v-model="form[type_enum.email].value"  placeholder="请输入乐马号/邮箱"/>
        </div>
        <div class="form-item fx fx-vc">
          <span class="form-label">登录密码</span>
          <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="form[type_enum.email].password" />
        </div>
      </div>

      <a class="btn btn-block btn-primary submit" :disabled="!valid_form" @click="submit($event)">{{posting ? '登录中' : '登录'}}</a>
      <a class="btn btn-block btn-primary btn-outline mt30" v-if="by == type_enum.phone || by == type_enum.potato" @click="changeLoginType">{{!isByVer ? '短信验证码' : '密码'}}登录</a>

      <div class="change-type fx fx-between fx-vc">
        <template v-if="by == type_enum.email" >
          <div>使用<a @click="changeRegisterType(type_enum.phone)">手机号码登录</a></div>
          <div>使用<a @click="changeRegisterType(type_enum.potato)">Potato登录</a></div>
        </template>
        <template v-else-if="by == type_enum.phone" >
          <div>使用<a @click="changeRegisterType(type_enum.email)">乐马号/邮箱登录</a></div>
          <div>使用<a @click="changeRegisterType(type_enum.potato)">Potato登录</a></div>
        </template>
        <template v-else >
          <div>使用<a @click="changeRegisterType(type_enum.email)">乐马号/邮箱登录</a></div>
          <div>使用<a @click="changeRegisterType(type_enum.phone)">手机号码登录</a></div>
        </template>
      </div>

      <div class="footer fx-center">
        <nuxt-link to="/forget_pwd">忘记密码</nuxt-link>
        <span>|</span>
        <nuxt-link to="/register">注册账号</nuxt-link>
      </div>
    </form>
  </div>
</template>

<script>
import Input from '~/components/Input'
import Password from '~/components/Password';

const type_enum =  {
  'phone': 1,
  'email': 2,
  'potato': 3,
}

/**
 * 为了保证切换登录方式的时候记录切换前的状态，
 * 以及选择区号时返回能记录之前的状态，
 * 每种登录方式需要的参数都给自保存在form里，
 * 以type_enmu为key保存
 */
export default {
  async asyncData(context) {
    const { store,route,query } = context;
    let rs = {
      by:query.type || 2,
      originType: query.originType,
      origin: query.origin,
    }

    await store.dispatch('register/setAreaCode');

    // 为了保证从区号选择返回是能带回之前的表单数据
    if(route.params.country && route.params.data){
      let { form, by } = route.params.data;
      form[by].area_code = route.params.country.code;
      rs = {form,by};
    }

    return rs;
  },
  components:{
    Input,
    Password,
  },
  data(){
    return {
      posting:false,
      form:{
        [type_enum.potato]:{
          area_code: this.$store.getters['register/getAreaCode'],
          value:'',
          password:'',
          ver_code:'',
          is_send:false,
          loading:false,
          ver_handel:null,
          ver_time:60
        },
        [type_enum.phone]:{
          area_code: this.$store.getters['register/getAreaCode'],
          value:'',
          password:'',
          ver_code:'',
          is_send:false,
          loading:false,
          ver_handel:null,
          ver_time:60
        },
        [type_enum.email]:{
          value:'',
          password:''
        },
      },
      isByVer:false,
      type_enum,
    }
  },
  computed:{
    valid_form(){
      let flag = true;
      let form = this.form[this.by];

      //如果是通过短信登录需要验证号码和验证码是否为空
      if((this.by == this.type_enum.phone || this.by == this.type_enum.potato)&& this.isByVer){
        flag = !!String(form.value).trim() && !!String(form.ver_code).trim()
      }else{
        flag = !!String(form.value).trim() && !!String(form.password).trim()
      }
      if(this.by !== this.type_enum.email){
        flag = flag && !!String(form.area_code).trim();
      }
      return flag && !this.posting;
    },
    ver_time_text(){
      let item = this.form[this.by];
      return !item.is_send ? (item.loading ? '加载中' : '获取验证码') : `${item.ver_time}s后重试`;
    }
  },
  async mounted(){
    if(this.$route.query.email){
      this.form[this.type_enum.email].value = this.$route.query.email
    }
    if(this.$store.state.token){
      await this.checkIsLogin();
    }
  },
  methods:{
    changeLoginType(){ // 修改登录方式
      this.form[this.by].password = '';
      this.form[this.by].ver_code = '';
      this.isByVer = !this.isByVer;
    },
    async getVerCode(e) { // 获取验证码
      let _form = this.form[this.by];
      console.log(_form)
      if(!this.isByVer || !_form.value || _form.loading || _form.ver_handel) return false;

      _form.loading = true;

      //获取验证码成功后input要获取焦点
      //这里不能反正ajax之后执行，浏览器处理机制问题
      try{
        let $input = e.target.parentNode.querySelector('input');
        $input && $input.focus();
      }catch(e){console.error(e)}

      let { data } = await this.$axios.post('?ct=member&ac=send_ver_code',{
        account:`${_form.area_code}${_form.value}`,
        action:'login',
        type:1,
      });

      if(data.code == 0 ){
        _form.is_send = true;
        _form.ver_handel = setInterval(()=>{
          try {
            if(_form.ver_time == 0) {
              clearInterval(_form.ver_handel);
              _form.ver_handel = null;
              _form.ver_time = 60;
            }
            _form.ver_time--;
          }catch(e){
            clearInterval(_form.ver_handel);
            _form.ver_handel = null;
            _form.ver_time = 60;
            this.$error(e);
          }
        },1000);

      }else{
        this.$toast(data.msg);
      }
      _form.loading = false;
    },
    async checkIsLogin(){
      try{
        let {data:rs} = await this.$axios.post('?ct=member&ac=token_login');
        if(rs.code == 0){
          const {data} = rs;
          this.$store.commit("SET_UID",data.uid);
          this.$store.commit("SET_TOKEN",data.token);
          this.$store.commit("SET_USER",data);
          this.$router.replace('/');
        }
      }catch(e){
      }
    },
    checkPassword(value){
      //后台录入的会员密码格式没有大写
      return true;
      var lv = 0;var val = value;
      if (val.match(/[A-Z]/g)) {
        lv++;
      }
      if (val.match(/[a-z]/g)) {
        lv++;
      }
      if (val.match(/[0-9]/g)) {
        lv++;
      }

      if (lv < 3 || value.length < 6 || value.length >30) {
        this.$toast('密码格式不正确');
        return false;
      } else {
        return true;
      }
    },
    changeAreaCode(){ // 修改手机区号
      // 缓存表单数据
      let {
          form,
          by
        } = this.$data;

      this.$router.push({name:'area_list',
       query:{from:'login'},
        params:{
          from:this.$route.name,
          data:{
            form,
            by
          }
        }
      });
    },
    changeRegisterType(by) {// 修改注册类型
      this.password = '';
      this.by = by;
    },
    async submit(){
      if(this.posting || !this.valid_form) return false;
      try{
        let form = this.form[this.by];

        if(!this.isByVer && !this.checkPassword(form.password)) return false;

        this.posting = true;

        let account = this.by == this.type_enum.email ? form.value : `${form.area_code}${form.value}`;
        let { data: rs } = await this.$axios.post('?ct=member&ac=login',{
          login_type:this.by,
          account,
          password:form.password,
          ver_code:this.isByVer ? form.ver_code : ''
        });

        if(rs.code == 0){
          const { data } = rs;
          if(data.is_need_reset_pwd == 1){ //第一次登录需要重置密码
            sessionStorage.setItem('recheck_user',JSON.stringify(data));
            this.$router.push({
              name:'login-password',
              query:{origin:this.origin, originType:this.originType, isNew: true},
            });
          }else{
            // 缓冲登录token，uid
            this.$store.commit("SET_UID",data.uid);
            this.$store.commit("SET_TOKEN",data.token);
            if(data.select_member == 1){ // 需要切换身份
              this.$router.push({
                name:'login-list',
                params:{list:data.group_labels,token:data.token},
                query:{origin:this.origin, originType:this.originType},
              })
            }else { // 正常登录成功
              this.$store.commit("SET_USER",data);

              // 扫描进来且没有完善资料  则进入完善资料页面
              if(this.origin == 4 && data.flow_status == 0) {
                this.$router.push({name:'complete_info'});
              } else {
                this.$router.replace('/');
              }
            }
          }
        }else{
          this.$toast(rs.msg);
          this.posting = false;
        }
      }catch(e){
        this.$error(e);
        this.posting = false;
      }
    }
  }
}
</script>


<style lang="less" scoped>
.page-conent {
    position: absolute;
    top:0;
    left:0;
    width:100%;
    height: 100%;
    padding:62px 50px 22px;
    background-color:#fff;
    h3 {
      margin-bottom:34px;
      line-height: 1;
      font-size:48px;
      color:#292929;
    }
    .form-item {
      & + .form-item {
        margin-top:20px;
      }
      .form-label,
      .ver-code {
        white-space: nowrap;
        line-height: 44px;
      }
      .ver-code  {
        display: block;
        font-size:30px;
        color:#2086f9;
        flex-shrink: 0;
        flex-grow: 0;
        width:160px;
        text-align: right;

        &[disabled] {
          opacity: .6;
        }
      }
      .form-label {
        width:130px;
        margin-right: 40px;
        font-size:30px;
        color:#292929;
      }
      input,select {
        display: block;
        -webkit-appearance: none;
        border:none;
        outline: none;
        height:40px;
        font-size:30px;
      }
      height:110px;
      border-bottom:1px solid #edeef0;
    }
  }
  .arrow {
      display: block;
      border-bottom:1px solid #999;
      border-left: 1px solid #999;
      width:10px;
      height:10px;
      transform: rotate(-45deg)
  }

  .agreement {
    font-size:24px;
    color:#666;
    margin:54px 0 30px;
    text-align: center;
  }
  .change-type {
    margin:24px auto;
    line-height: 64px;
    text-align: center;
    font-size:30px;
    color:#666;
    a {
      color: @color-primary
    }
  }

  .footer {
    position: absolute;
    text-align: center;
    left:0;
    right:0;
    bottom:58px;
    margin:auto;
    font-size:30px;
    color:#666;
    span {
      padding:0 44px;
    }
  }

  .submit {
    margin-top:58px;
  }
</style>
